package com.yiboshi.rehrs.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.domain.entity.RechargeCard;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.mapper.RechargeCardMapper;
import com.yiboshi.rehrs.domain.service.IRechargeCardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.exception.ZyantExceptionUtils;
import com.yiboshi.rehrs.util.DingdingUtils;
import com.yiboshi.rehrs.util.RechargeCardUtil;
import com.yiboshi.rehrs.util.StrUtils;
import com.yiboshi.rehrs.util.ThreadPoolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author local
 * @since 2025-04-03
 */
@Service
public class RechargeCardServiceImpl extends AperBaseServiceImpl<RechargeCardMapper, RechargeCard> implements IRechargeCardService {

    @Autowired
    IZhongUserService zhongUserService;

    @Override
    public RechargeCard getOne(String cardNo) {
        boolean valid = RechargeCardUtil.checkRechargeCode(cardNo);
        if(!valid){
            return null;
        }
        LambdaQueryWrapper<RechargeCard> eq = getQueryWrapper().eq(RechargeCard::getCardNo, cardNo);
        return getOne(eq);
    }

    //1成功；0无效；2已经试用过了不能再试用
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int exchange(RechargeCard rechargeCard, ZhongUser zhongUser) {
        LocalDateTime now = LocalDateTime.now();
        Integer daysNum = rechargeCard.getDaysNum();
        if(Objects.equals(rechargeCard.getCardType(),0)){//试用卡
            String account = zhongUser.getAccount();
            //查询是否试用过
            LambdaQueryWrapper<RechargeCard> cardLambdaQueryWrapper = getQueryWrapper()
                    .eq(RechargeCard::getVipAcount, account)
                    .eq(RechargeCard::getUsedStatus,1)
                    .eq(RechargeCard::getCardType,0);
            int count = count(cardLambdaQueryWrapper);
            if(count>0){
                return 2;
            }
        }
        LambdaUpdateWrapper<RechargeCard> updateWrapper = getUpdateWrapper().eq(RechargeCard::getId, rechargeCard.getId())
                .eq(RechargeCard::getUsedStatus, 0)
                .set(RechargeCard::getUsedStatus, 1)
                .set(RechargeCard::getVipAcount, zhongUser.getAccount())
                .set(RechargeCard::getUsedTime, now);
        boolean update = this.update(updateWrapper);

        if(update){
            LocalDateTime vipExpDate = zhongUser.getVipExpDate();
            if(vipExpDate==null||vipExpDate.isBefore(now)){
                vipExpDate = now;
            }
            vipExpDate = vipExpDate.plusDays(daysNum);
            LambdaUpdateWrapper<ZhongUser> updateWrapper1 = zhongUserService.getUpdateWrapper()
                    .eq(ZhongUser::getId,zhongUser.getId())
                    .eq(ZhongUser::getAccount,zhongUser.getAccount())
                    .set(ZhongUser::getVipExpDate,vipExpDate)
                    .set(ZhongUser::getAgentAccount,rechargeCard.getAgentAccount())
                    .set(zhongUser.getAutoStatus()!=null,ZhongUser::getAutoStatus,zhongUser.getAutoStatus())
                    .set(zhongUser.getAutoTaskType()!=null,ZhongUser::getAutoTaskType,zhongUser.getAutoTaskType())
                    ;
            zhongUser.setVipExpDate(vipExpDate);
            boolean update1 = zhongUserService.update(updateWrapper1);
            if(update1){
                dingdingMsg(rechargeCard,zhongUser);
            }else{
                ZyantExceptionUtils.e(true,zhongUser.getAccount()+"充值失败，请重试");
            }

            return 1;
        }else{
            //已经使用 或者不存在
            return 0;
        }
    }

    @Override
    public void deleteByTime() {
        remove(getQueryWrapper()
                .eq(RechargeCard::getCardType,0)
                .eq(RechargeCard::getUsedStatus,0)
                .lt(RechargeCard::getCreateTime,LocalDateTime.now().plusDays(-40)));
    }

    private void dingdingMsg(RechargeCard rechargeCard,ZhongUser zhongUser) {
        ThreadPoolUtils.submitTask(()->{
            try {
                String agentAccount = rechargeCard.getAgentAccount();
                if(StrUtils.isNotBlank(agentAccount)&&agentAccount.length()>4){
                    ZhongUser agentUser = zhongUserService.one(agentAccount);
                    if(agentUser!=null&&agentUser.getAccount().equals("2153011500166")){
                        DingdingUtils.sendMessageByLocal(RehrsSystemConfig.getProfile()+"\n"+rechargeCard.getDaysNum()+"天卡"+ rechargeCard.getCardNo()+"充值成功.账号"
                                        +zhongUser.getAccount()+",电话"+zhongUser.getTelephone()+",到期时间:"+ zhongUser.getVipExpDate(),
                                agentUser.getTelephone());
                    }
                }
            }catch (Exception e){
                log.error("",e);
            }

        });
    }
}
